package com.bionic.banking.logic.controller;

import com.bionic.banking.core.entity.BankAccount;
import com.bionic.banking.core.entity.BankTransaction;
import com.bionic.banking.dao.IBankAccountDao;
import com.bionic.banking.dao.classes.BankAccountDaoImp;
import com.bionic.banking.dao.connection.LoggerLoader;
import com.bionic.banking.logic.IBankAccountController;
import com.bionic.banking.logic.exception.InvalidParameterException;
import java.sql.SQLException;
import java.util.*;

public class BankAccountController extends AbstractBean<BankAccount> implements IBankAccountController {

    private static final org.apache.log4j.Logger logger = LoggerLoader.getLogger(CustomerController.class);
    
    @Override
    protected IBankAccountDao getDaoObject() {
        return new BankAccountDaoImp(); 
    }

    public BankAccountController() throws InstantiationException, IllegalAccessException {
        super();
    }

    @Override
    public List<BankTransaction> getBankAccountTransactions(Date startDate, Date endDate, Integer accountId)
            throws SQLException, InvalidParameterException , InstantiationException, IllegalAccessException
    {
        BankTransactionController transactionBean = new BankTransactionController();
        return transactionBean.getAccountBankTransactions(startDate, endDate, accountId);            
    }

    @Override
    public List<BankAccount> getCustomerAccounts(Integer customerId)
            throws InvalidParameterException, SQLException {
        if (customerId == null) {
            throw new InvalidParameterException("null customerId");
        }
        return getDaoObject().findByCustomerId(customerId);
    }

    public List<Integer> getCustomerAccountsIds(Integer customerId)
            throws InvalidParameterException, SQLException {

        List<BankAccount> list = getCustomerAccounts(customerId);
        List<Integer> idsList = new ArrayList<>();
        for (BankAccount account : list) {
            idsList.add(account.getAccountId());
        }
        return idsList;
    }

    @Override
    public void removeCustomerAccounts(Integer customerId) throws InvalidParameterException, SQLException {
        List<Integer> bankAccounts = getCustomerAccountsIds(customerId);
        for (Integer accountId : bankAccounts) 
        {
            //1.remove related transactions            
            BankTransactionController txController;
            try {
                txController = new BankTransactionController();
                txController.removeCustomerBankTransactions(customerId);
            } catch (InstantiationException | IllegalAccessException ex) {
                logger.error(ex);
            }
            //2. remove account
            remove(accountId);
        }
    }
}